$(function(){ 

    //var log = console.log; 
    var $content = $('#content');  

    //The Form itself
    $content.find('#frm_img').wl_Form({
        submitButton: 'button.submit',
        resetButton: 'button.reset',
        method: 'post',
        action: null,
        ajax: true,
        serialize: false,
        parseQuery: true,
        dataType: 'text',
        status: true,
        sent: false,
        confirmSend: true,
        text: {
            required: 'Ovo polje je obavezno',
            valid: 'Ovo polje nije u redu',
            password: 'Lozinka je kratka',
            passwordmatch: 'Ovaa lozinka se ne poklapa',
            fileinqueue: 'Postoji najmanje jedan fajl na čekanju',
            incomplete: 'Molimo popunite formu ispravno!',
            send: 'pošalji formu...',
            sendagain: 'pošalji ponovo?',
            success: 'forma poslata!',
            error: 'greška prilikom slanja!',
            parseerror: 'Nemogu da deserializujem query string:\n %e'
        },
        tooltip: {
            gravity: 'nw'
        },
        onRequireError: function (element) {},
        onValidError: function (element) {},
        onPasswordError: function (element) {},
        onFileError: function (element) {},
        onBeforePrepare: function () {

            $('#srvrserror-3').hide();

            var chk = $('#directory').val();
            var chk2 = $('#filename').val();
            //console.log('chk2:'+chk2)

            if(chk==0){

                $('#srvrserror-3').html('molimo odaberite direktorijum');
                $('#srvrserror-3').show('slow');

            }else if(chk2==''){ 

                $('#srvrserror-3').html('molimo odaberite fajl za upload');
                $('#srvrserror-3').show('slow');

            }else {

                // When all files are uploaded submit form
                loader();

                $.ajax({
                    type: "POST",
                    url: base_url+'media/edit_insert',
                    data: {
                        id: get_id, 
                        parent: $("#directory").val(),  
                        name: $("#name").val(),
                        description: $("#description").val(),
                        author: $("#author").val(),
                        tags: $("#tags").val(), 
                        filename: $("#filename").val(), 
                        appmode: appmode,
                        type: $("#type").val()
                    },
                    dataType: 'json',
                    success: function(data){

                        if(data.action==true){

                            $.modal.close();
                            /*----------------------------------------------------------------------*/
                            /* go to preview article url 
                            /*----------------------------------------------------------------------*/
                            document.location.href = base_url + 'media/preview';

                        }else{

                            alert('Molim odaberte sva polja.'+data.msg)

                        }


                    }
                }) 

            }

            return false;
        },
        onBeforeSubmit: function (data) {},
        onReset: function () {},
        onComplete: function (textStatus, jqXHR) {},
        onError: function (textStatus, error, jqXHR) {},
        onSuccess: function (data, textStatus, jqXHR) {}
    }); 

    /***********************************************************
    * LOADERS
    ***********************************************************/    

    function loader()
    {
        $.modal(
        "<div><div class='animate'><img src='"+base_url+"assets/img/backgnds/loading.gif'></div><h2>Molim sačekajte...</h2></div>" , {
            closeHTML: "",
            containerCss:{
                height:70,
                width:120,
                borderColor:"#dedede"
            },
            opacity:20,
            overlayCss: {
                backgroundColor: "#000000"
            }
        });
    }

    /***********************************************************
    * PLUPLOAD FILE UPLOEADER
    ***********************************************************/  

    var folder = 'tempatt/';

    var uploader = new plupload.Uploader({

        runtimes: 'flash',
        flash_swf_url: base_url+'assets/js/plupload/plupload.flash.swf',
        browse_button: 'pickfiles',
        container: 'uploader',
        url: base_url+'assets/js/plupload/upload.php',
        multipart : false,
        multipart_params: { 'datafield': folder },
        unique_names: true ,
        // Specify what files to browse for
        filters : [
        {title : "Image files", extensions : "jpg,jpeg,gif,png,wav"}
        ],
        multi_selection:false

    });


    uploader.settings.multipart_params.datafield = folder;    

    //console.log(uploader.settings.multipart_params.datafield)


    uploader.init();

    uploader.bind('FilesAdded', function(up, files) {        
        // loop through the files array
        for (var i in files) {            
            document.getElementById('filelist').innerHTML += '<div id="' + files[i].id + '">' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';            
        }
        //console.log(uploader.settings.multipart_params.datafield)  
    });

    uploader.bind('UploadProgress', function(up, file) {        
        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";        
    });

    uploader.bind('Error', function(up, args) {        
        alert(args.code + ': ' + args.message);        
    });

    document.getElementById('uploadfiles').onclick = function() {         
        uploader.start();         
    };

    uploader.bind('FileUploaded', function(up, file, info) {
        //console.log("uploaded");

        if( (uploader.total.uploaded + 1) == uploader.files.length) {
            //window.location = 'uploaded.php?file=' + encodeURIComponent(File.name);
            //console.log("uploaded complete");
        };

        //console.log('[FileUploaded] up:', up,' File:', file, "Info:", info);

        fname = file.target_name;

        //console.log('encodeURIComponent: '+fname)                        

        $('#filename').val(fname);
        $('#displayImage').show();
        $('#displayImage img').attr('src', base_url+'tempatt/'+fname);

    });

    /*----------------------------------------------------------------------*/
    /* Breadcrumb
    /*----------------------------------------------------------------------*/

    /*$content.find('ul.breadcrumb').wl_Breadcrumb({
    start : 0,
    locked: false,
    disabled: false,
    onChange: function(element,id){}
    });*/


});
